<!DOCTYPE html>
<html>
{{template "bodyHead" `<link rel="stylesheet" type="text/css" href="/css/adminHome.css?v=1.0"/>`}}
<body>

{{template "inc_header" .}}

<div id="main">
    <div id="main-inner">

    {{template "adminMainInfo" .}}

    {{template "adminMainNav" "types"}}

        <div id="admin-types-main" class="clouds">
            <h3 class="clouds-title" id="admin-page-title">分类管理</h3>
            <div class="admin-types-main">
                <pre id="postTypesAll-pre">
                </pre>
            </div>
        </div>

    </div>
</div>

<!-- 添加/修改分类模态框 -->
<div id="typeModal" class="modal" style="display: none;">
    <div class="modal-content">
        <span class="close">&times;</span>
        <h3 id="modalTitle">添加分类</h3>
        <form id="typeForm">
            <input type="hidden" id="typeId" name="id" value="">
            <div class="form-group">
                <label for="typeName">分类名称:</label>
                <input type="text" id="typeName" name="name" required>
            </div>
            <div class="form-group">
                <label for="typeFid">父级分类:</label>
                <select id="typeFid" name="fid">
                    <option value="0">根分类</option>
                </select>
            </div>
            <div class="form-group">
                <label for="typeReadLevel">阅读权限:</label>
                <select id="typeReadLevel" name="read_level">
                    <option value="0">公开</option>
                    <option value="1">登录可见</option>
                    <option value="2">管理员可见</option>
                </select>
            </div>
            <div class="form-group">
                <label for="typeIsShow">是否显示:</label>
                <select id="typeIsShow" name="is_show">
                    <option value="1">显示</option>
                    <option value="0">隐藏</option>
                </select>
            </div>
            <div class="form-actions">
                <button type="submit" class="btn-primary">保存</button>
                <button type="button" class="btn-secondary" onclick="closeModal()">取消</button>
            </div>
        </form>
    </div>
</div>

<!-- 删除确认模态框 -->
<div id="deleteModal" class="modal" style="display: none;">
    <div class="modal-content">
        <h3>确认删除</h3>
        <p id="deleteMessage">确定要删除这个分类吗？</p>
        <div class="form-actions">
            <button type="button" class="btn-danger" onclick="confirmDelete()">确认删除</button>
            <button type="button" class="btn-secondary" onclick="closeDeleteModal()">取消</button>
        </div>
    </div>
</div>

{{template "inc_footer" .}}

<style>
.modal {
    position: fixed;
    z-index: 1000;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0,0,0,0.4);
}

.modal-content {
    background-color: #fefefe;
    margin: 15% auto;
    padding: 20px;
    border: 1px solid #888;
    width: 400px;
    border-radius: 5px;
}

.close {
    color: #aaa;
    float: right;
    font-size: 28px;
    font-weight: bold;
    cursor: pointer;
}

.close:hover {
    color: black;
}

.form-group {
    margin-bottom: 15px;
}

.form-group label {
    display: block;
    margin-bottom: 5px;
    font-weight: bold;
}

.form-group input,
.form-group select {
    width: 100%;
    padding: 8px;
    border: 1px solid #ddd;
    border-radius: 4px;
}

.form-actions {
    text-align: right;
    margin-top: 20px;
}

.btn-primary {
    background-color: #007cba;
    color: white;
    padding: 10px 20px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    margin-right: 10px;
}

.btn-secondary {
    background-color: #6c757d;
    color: white;
    padding: 10px 20px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

.btn-danger {
    background-color: #dc3545;
    color: white;
    padding: 10px 20px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    margin-right: 10px;
}

.btn-primary:hover { background-color: #005a87; }
.btn-secondary:hover { background-color: #545b62; }
.btn-danger:hover { background-color: #c82333; }
</style>

<script>
var currentDeleteId = null;

$(function(){
    loadTypes();
    
    // 关闭模态框
    $('.close').click(function() {
        closeModal();
    });
    
    // 点击模态框外部关闭
    $(window).click(function(event) {
        if (event.target == document.getElementById('typeModal')) {
            closeModal();
        }
        if (event.target == document.getElementById('deleteModal')) {
            closeDeleteModal();
        }
    });
    
    // 表单提交
    $('#typeForm').submit(function(e) {
        e.preventDefault();
        saveType();
    });
});

function loadTypes() {
    $.ajax({
        url:"/admin/types/all",
        method:"GET",
        dataType:"json",
        success:function (d) {
            if (!d || !d.data || !Array.isArray(d.data) || d.data.length < 1) {
                $('#postTypesAll-pre').html("暂无分类数据");
                return;
            }

            var str = "    <span>根分类</span><a href='javascript:addType(0);'>添加</a>\r\n";
            var m = 0;
            for(var i in d.data){
                var n = 0;
                if ((m+1)==d.data.length){
                    str +="    <span>  └───["+d.data[i].post_num+"]<i _id='"+d.data[i].id+"' >"+d.data[i].name+"</i><a href='javascript:addType("+d.data[i].id+");'>添加</a><a href='javascript:editType("+d.data[i].id+");'>修改</a><a href='javascript:deleteType("+d.data[i].id+",\""+d.data[i].name+"\");'>删除</a></span>\r\n";
                    if (d.data[i].child && Array.isArray(d.data[i].child)) {
                        for (var x in d.data[i].child) {
                            if ((n+1)==d.data[i].child.length){
                                str +="    <span>           └───["+d.data[i].child[x].post_num+"]<i _id='"+d.data[i].child[x].id+"' >"+d.data[i].child[x].name+"</i><a href='javascript:editType("+d.data[i].child[x].id+");'>修改</a><a href='javascript:deleteType("+d.data[i].child[x].id+",\""+d.data[i].child[x].name+"\");'>删除</a></span>\r\n";
                            }else{
                                str +="    <span>           ├───["+d.data[i].child[x].post_num+"]<i _id='"+d.data[i].child[x].id+"' >"+d.data[i].child[x].name+"</i><a href='javascript:editType("+d.data[i].child[x].id+");'>修改</a><a href='javascript:deleteType("+d.data[i].child[x].id+",\""+d.data[i].child[x].name+"\");'>删除</a></span>\r\n";
                            }
                            n++;
                        }
                    }
                } else{
                    str +="    <span>  ├───["+d.data[i].post_num+"]<i _id='"+d.data[i].id+"' >"+d.data[i].name+"</i><a href='javascript:addType("+d.data[i].id+");'>添加</a><a href='javascript:editType("+d.data[i].id+");'>修改</a><a href='javascript:deleteType("+d.data[i].id+",\""+d.data[i].name+"\");'>删除</a></span>\r\n";
                    if (d.data[i].child && Array.isArray(d.data[i].child)) {
                        for (var x in d.data[i].child) {
                            if ((n+1)==d.data[i].child.length){
                                str +="    <span>  │        └───["+d.data[i].child[x].post_num+"]<i _id='"+d.data[i].child[x].id+"' >"+d.data[i].child[x].name+"</i><a href='javascript:editType("+d.data[i].child[x].id+");'>修改</a><a href='javascript:deleteType("+d.data[i].child[x].id+",\""+d.data[i].child[x].name+"\");'>删除</a></span>\r\n";
                            }else{
                                str +="    <span>  │        ├───["+d.data[i].child[x].post_num+"]<i _id='"+d.data[i].child[x].id+"' >"+d.data[i].child[x].name+"</i><a href='javascript:editType("+d.data[i].child[x].id+");'>修改</a><a href='javascript:deleteType("+d.data[i].child[x].id+",\""+d.data[i].child[x].name+"\");'>删除</a></span>\r\n";
                            }
                            n++;
                        }
                    }
                }
                m++;
            }
            $('#postTypesAll-pre').html(str);
            
            // 更新父级分类选择框
            updateParentSelect(d.data);
        },
        error: function(xhr, status, error) {
            console.error('获取分类数据失败:', error);
            $('#postTypesAll-pre').html("获取分类数据失败，请刷新页面重试");
        }
    });
}

function updateParentSelect(types) {
    var select = $('#typeFid');
    select.find('option:not(:first)').remove();
    
    function addOptions(data, level) {
        var prefix = '　'.repeat(level);
        for (var i in data) {
            select.append('<option value="' + data[i].id + '">' + prefix + data[i].name + '</option>');
            if (data[i].child && data[i].child.length > 0) {
                addOptions(data[i].child, level + 1);
            }
        }
    }
    
    addOptions(types, 0);
}

function addType(parentId) {
    $('#modalTitle').text('添加分类');
    $('#typeForm')[0].reset();
    $('#typeId').val('');
    $('#typeFid').val(parentId);
    $('#typeModal').show();
}

function editType(id) {
    $('#modalTitle').text('修改分类');
    
    // 获取分类信息
    $.ajax({
        url: "/admin/types/info/" + id,
        method: "GET",
        dataType: "json",
        success: function(d) {
            if (d && d.data) {
                $('#typeId').val(d.data.id);
                $('#typeName').val(d.data.name);
                $('#typeFid').val(d.data.fid);
                $('#typeReadLevel').val(d.data.read_level);
                $('#typeIsShow').val(d.data.is_show);
                $('#typeModal').show();
            }
        },
        error: function() {
            alert('获取分类信息失败');
        }
    });
}

function saveType() {
    var formData = new FormData($('#typeForm')[0]);
    var url = $('#typeId').val() ? '/admin/types/update' : '/admin/types/add';
    
    $.ajax({
        url: url,
        method: "POST",
        data: formData,
        processData: false,
        contentType: false,
        success: function(d) {
            if (d.error === 0) {
                alert('保存成功');
                closeModal();
                loadTypes();
            } else {
                alert('保存失败: ' + d.message);
            }
        },
        error: function() {
            alert('保存失败，请重试');
        }
    });
}

function deleteType(id, name) {
    currentDeleteId = id;
    $('#deleteMessage').text('确定要删除分类 "' + name + '" 吗？删除后该分类下的文章将变为未分类状态。');
    $('#deleteModal').show();
}

function confirmDelete() {
    if (!currentDeleteId) return;
    
    $.ajax({
        url: "/admin/types/delete",
        method: "POST",
        data: {id: currentDeleteId},
        success: function(d) {
            if (d.error === 0) {
                alert('删除成功');
                closeDeleteModal();
                loadTypes();
            } else {
                alert('删除失败: ' + d.message);
            }
        },
        error: function() {
            alert('删除失败，请重试');
        }
    });
}

function closeModal() {
    $('#typeModal').hide();
}

function closeDeleteModal() {
    $('#deleteModal').hide();
    currentDeleteId = null;
}
</script>
</body>
</html>